from rest_framework import serializers

from system.serializers import DepartmentSerializers
from .models import *
from system.models import Department
from rest_framework.validators import UniqueTogetherValidator



class UserRoleSerializers(serializers.ModelSerializer):
    department=DepartmentSerializers()
    class Meta:
        model=Role
        fields='__all__'

class RoleSerializers(serializers.ModelSerializer):
    #解决方案1：
    # 序列化时使用StringRelatedField() 返回关联对象的字符串描述
    # 反序列化时 在序列化器中 定义一个接收关联模型的主键id字段
    # department=serializers.StringRelatedField()
    # department_id=serializers.IntegerField(write_only=True)
    #解决方案2：
    department=serializers.SlugRelatedField(slug_field='name',queryset=Department.objects.all())
    class Meta:
        model = Role
        fields= '__all__'
        validators = [UniqueTogetherValidator(queryset=Role.objects.all(), fields=('role_name', 'department'), message='该职位已存在，无需重复添加！')]

class AdminUserSerializers(serializers.ModelSerializer):
    class Meta:
        model = AdminUser
        exclude=['groups','user_permissions','is_staff']
        read_only_fields = ['last_login','date_joined']
        extra_kwargs = {'password': {'write_only': True}}
    def create(self, validated_data):
        user=super().create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user
    def update(self, instance, validated_data):
        instance=super().update(instance,validated_data)
        if validated_data.get('password'):
            instance.set_password(validated_data['password'])
            instance.save()
        return instance


class UserAppraisalSerializers(serializers.ModelSerializer):
    def create(self, validated_data):
        print(validated_data)
        # user=super().create(validated_data)
        # user.set_password(validated_data['password'])
        # user.save()
        return {}

    class Meta:
        model=UserAppraisal
        fields='__all__'

class AppraisalQuestionBankSerializers(serializers.ModelSerializer):
    class Meta:
        model=AppraisalQuestionBank
        fields='__all__'